package com.dianqiu.batch.service.impl;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.dianqiu.base.util.DateUtil;
import com.dianqiu.batch.bean.DqTempMatchesTO;
import com.dianqiu.batch.dao.DqTempMatchDao;
import com.dianqiu.batch.service.CrawlerService;
@Component("dinaCrawlerService")
public class SinaCrawlerServiceImpl implements CrawlerService{
	private Logger logger = LoggerFactory.getLogger(SinaCrawlerServiceImpl.class);
	private DqTempMatchDao dqTempMatchDao;
	private static final String[] matchType = {"正在进行的比赛","将要进行的比赛","已经完成的比赛"};
	
	public DqTempMatchDao getDqTempMatchDao() {
		return dqTempMatchDao;
	}
	@Resource
	public void setDqTempMatchDao(DqTempMatchDao dqTempMatchDao) {
		this.dqTempMatchDao = dqTempMatchDao;
	}

	public void crawl(String url,String userAgent,int timeout) throws Exception{
		
		getDqTempMatchDao().delete();
		
		logger.info("Begin to crawl info from site <"+url+">");
		logger.info("User agent is <"+userAgent+">");
		logger.info("Timeout is <"+timeout+">");
		Document docs = getResource(url, userAgent, timeout);
		try {
			if (docs == null) {
				logger.error("Can't get resource from url <"+url+">");
				return;
			}
			List<DqTempMatchesTO> matchList = parse(docs);
			getDqTempMatchDao().save(matchList);
		} catch (ParseException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}
	
	private Document getResource(String url,String userAgent,int timeout){
		Document document = null;
		try {
			 document = Jsoup.connect(url).userAgent(userAgent).timeout(timeout).get();
		} catch (IOException e) {
			logger.error("Crawl info from <"+url+"> hit error");
			logger.error(e.getMessage(), e);
		}
		return document;
	}
	
	private List<DqTempMatchesTO>  parse(Document docs) throws ParseException{
		List<Element> res = parseFatherNode(docs);
		List<DqTempMatchesTO> tos = new ArrayList<DqTempMatchesTO>();
		for (int i = 0; i < res.size(); i++) {
			tos = parseChildNode(res.get(i), tos, i, "tr");
		}
		return tos;
	}
	
	private List<Element> parseFatherNode(Document docs){
		logger.info("Begin to parse father node");
		List<Element> result = new ArrayList<Element>();
		Element gameInTime = docs.getElementById("m0");
		result.add(gameInTime);
		Element gameTo = docs.getElementById("m1");
		result.add(gameTo);
		Element gameDone = docs.getElementById("m2");
		result.add(gameDone);
		logger.info("End to parse father node with size : <"+result.size()+">");
		return result;
	}
	
	private List<DqTempMatchesTO> parseChildNode(Element element,List<DqTempMatchesTO> list,int matchTypeID,String tagName) throws ParseException{
		logger.info("Begin to parse father node : "+element);
		logger.info("Begin to parse child node with matchTypeID : <"+matchTypeID+"> tagName : <"+tagName+">");
		List<Element> childElements = null;
		boolean hasElements = false;
		if (element != null) {
			childElements = element.getElementsByTag(tagName);
			if(childElements.size() > 2){
				hasElements = true;
			}
		}
		
		if (hasElements) {
			logger.info("Current element contains useful info");
			logger.info("Begin to generate DqTempMatchesTOs");
			for (int i = 2; i < childElements.size(); i++) {
				String text = childElements.get(i).text();
				logger.info("Current child element text is : <"+text+">");
				DqTempMatchesTO to = divStr(text);
				if (to != null) {
					to.setMatchType(matchType[matchTypeID]);
					list.add(to);
				}
			}
		}
		return list;
	}
	
	private DqTempMatchesTO divStr(String text) throws ParseException{
		if(StringUtils.isBlank(text)){
			return null;
		}
		
		String[] div = text.split(" ");
		if(div == null || div.length < 8){
			return null;
		}
		
		DqTempMatchesTO to = new DqTempMatchesTO();
		to.setMatchName(div[0]);
		to.setMatchTime((Timestamp)DateUtil.formatStr2Timestamp("2012-"+div[1]+" "+div[2]+":00", "yyyy-MM-dd hh:mm:ss"));
		to.setMatchStatus(div[3]);
		to.setHostTeam(div[4]);
		to.setMatchGoal(div[5]);
		to.setGuestTeam(div[6]);
		to.setHalfMatchGoal(div[7]);
		to.setCreatedBy("SYSTEM");
		to.setCreatedDt(new Timestamp(System.currentTimeMillis()));
		to.setUpdatedBy("SYSTEM");
		to.setUpdatedDt(new Timestamp(System.currentTimeMillis()));
		return to;
	}
	
//	public static void main(String[] args) {
//		SinaCrawlerServiceImpl s = new SinaCrawlerServiceImpl();
//		s.crawl("http://sports.sina.com.cn/live/", null, 0);
//	}

}
